<?php
if (!defined('DEBUG_SQL'))
  define ('DEBUG_SQL', '1');
  
class mySqlClient
{
  var $link;
  var $tables;

  function __construct($user = "", $password = "", $server = "", $database = "")
  {
    if (
      $server && $user && $database &&
      $this->connect($server, $user, $password)&&
      $this->selectDB($database)&&
      $this->getTables()
    );
  }

  function connect($server, $user, $password)
  {    
    $this->link = mysql_connect($server, $user, $password);
    if (!$this->link)
    {
      trigger_error("Couldn't connect: ".mysql_error(), E_USER_ERROR);
      return false;
    }
    else
    {
      $this->query("SET NAMES utf8");
      return true;
    }
  }

  function query($sql)
  {
    $res = mysql_query($sql, $this->link);

    if (!$res)
      trigger_error(mysql_error().(DEBUG_SQL?" [SQL: $sql]":""), E_USER_ERROR);

    return $res;
  }

  function selectDB($database, $createIfMissing = false)
  {
    return
      mysql_select_db($database,$this->link) or
      (
        $this->query("CREATE DATABASE $database DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci") and
        mysql_select_db($database,$this->link)
      );
  }

  function getTables()
  {
    $this->tables = array();
    $res = $this->query("SHOW TABLES");

    if ($res===false) 
      return false;

    while ($row = mysql_fetch_row($res))
      $this->tables[$row[0]]=$row[0];

    return true;
  }

  function addTable($sql)
  {
    return $this->query($sql) and $this->getTables();
  }

}
?>
